package com.usian.admin.gateway.utils.filter;

import com.usian.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断当前的请求是否为登录，如果是直接放行
        if (request.getPath().value().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }
        //获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        List<String> tokens = headers.get("token");
        //判断当前令牌是否存在
        if (tokens == null || tokens.size() == 0 || StringUtils.isBlank(tokens.get(0))) {
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        try {
            //5.如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
            String token = tokens.get(0);
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == 0 || i == -1) {
                // 合法，则向header中重新设置userId
                Integer id = (Integer) claims.get("id");
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", id + "")).build();
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            String json = "{\"errorMsg\":\"token is invalid\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
